package com.byd.android.mediaplayer;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import com.byd.android.Socket.SocketServer;
import com.byd.android.VideoPlayer.AbstructProvider;
import com.byd.android.VideoPlayer.VideoProvider;
import com.byd.android.agreement.InstructionList;
import com.byd.android.agreement.message.MediaList;
import com.byd.android.agreement.message.Messages;
import com.byd.android.agreement.message.Music;
import com.byd.android.agreement.message.MusicList;
import com.byd.android.agreement.message.Video;
import com.byd.android.agreement.order.Order;
import com.byd.android.agreement.order.OrderMessage;
import com.byd.android.agreement.order.Params;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import static com.byd.android.agreement.InstructionList.DATA_OP.GET_LIST;
import static com.byd.android.agreement.InstructionList.MODE.MODE_MUSIC;
import static com.byd.android.agreement.InstructionList.MODE.MODE_VIDEO;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_BACK;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_CONTINUE;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_CURRENTDURATION;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_DONOTHING;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_NEXT;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PAUSE;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PLAY;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PREVIOUS;
import static com.byd.android.agreement.message.MediaList.MEDIA_TYPE_MUSIC;
import static com.byd.android.agreement.message.MediaList.MEDIA_TYPE_VIDEO;

public class MediaService extends Service {
    public int MODE;

    public static final int DATA_IMAGE = 0x504;

    public static final String TAG = "MediaService";

    private Handler mHandlerMedia;

    private ContentResolver contentResolver;

    private Cursor mCursor;

    public List<Music> musicList = new ArrayList<>();

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private int currentMediaIndex = -1;

    public boolean Running = true;

    public boolean pauseTrue = true;

    private SocketServer socketServer;

    public List<Video> videoList = new ArrayList<>();
    
    public Intent intent;

    public MediaService instance = null;

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");
        createNotificationChannel();
        initSocketServer();

        //收到消息
        SocketServer.ServerHandler = new Handler(  ){
            @Override
            public void handleMessage(Message msg)
            {
                try {
                    mHandlerMedia.sendEmptyMessage(ORDER_DONOTHING);
                    String str = new String((byte[]) msg.obj, "UTF-8");
                    Log.d(TAG, "handleMessage: " + str);
                    recvOrderMessage(str);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };



    }


    private void initSocketServer() {
        try {
            socketServer = new SocketServer(34569);
            socketServer.beginListen2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createNotificationChannel() {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道的id
        String id = this.getPackageName();
        // 用户可以看到的通知渠道的名字.
        CharSequence name = this.getClass().getSimpleName();
//         用户可以看到的通知渠道的描述
        String description = name.toString();
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
//         配置通知渠道的属性
        mChannel.setDescription(description);
//         设置通知出现时的闪灯（如果 android 设备支持的话）
        mChannel.enableLights(true); mChannel.setLightColor(Color.RED);
//         设置通知出现时的震动（如果 android 设备支持的话）
//        mChannel.enableVibration(true);
//        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//         最后在notificationmanager中创建该通知渠道 //
        mNotificationManager.createNotificationChannel(mChannel);

        // 为该通知设置一个id
        int notifyID = 1;
        // 通知渠道的id
        String CHANNEL_ID = "my_channel_01";
        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(this, id)
                .setContentTitle("New Message") .setContentText("You've received new messages.")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
        startForeground(1,notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        socketServer.close();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();

        }
        Running = false;
        Log.d(TAG, "onDestroy: service is finish");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override

    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind:is onCreate ");

        return new MediaBinder();
    }


    //Binder绑定的实现类，可以接受来自UI的改变播放状态的命令,Music播放类
    public class MediaBinder extends Binder {
        //通用方法
        public void sendHandler(Handler handler) {
            mHandlerMedia = handler;
        }

        public void distoryHandler() {
            mHandlerMedia = null;
        }

        //主界面方法，从主界面得到服务端的点击事件
        public void getMode(int mode) {
            MODE = mode;
            switch (MODE) {
                case MODE_MUSIC:
                    initMusicService();
                    break;
                case MODE_VIDEO:
                    //视频在服务中不需要初始化
                    initVideoService();
//                   message = new Message();
//                   message.what = MODE_VIDEO;
//                   mHandlerMedia.sendMessage(message);
                    break;
                default:
                    break;
            }
        }

        //音乐播放器方法


        public void play(int Index) {
            currentMediaIndex = Index;
            Log.d(TAG, "play: click receive is " + currentMediaIndex);
            MediaService.this.play();
        }

        public void play() {
            mediaPlayer.start();
        }

        public void pause() {
            MediaService.this.pause();
        }

        public void previous(int Index) {
            currentMediaIndex = Index;
            MediaService.this.previous();
        }

        public void next(int Index) {
            Log.d("EEEEEEEEEEEEEEEE", "on nexttttttt!!!!");
            currentMediaIndex = Index;
            MediaService.this.next();
        }

        public boolean playing() {
            return mediaPlayer.isPlaying();
        }

        public void seek(int position) {
            changeProgress(position);
        }

        public void stop(boolean reset) {
            MediaService.this.stop();

            if (reset) {
                MediaService.this.reset();
            }
        }

        //返回Music列表给UI
        public List<Music> getMusicList() {
            return MediaService.this.musicList;

        }

        //返回Video列表给Service
        public void sendVideoList(List<Video> VList){
           videoList = VList;
       //     Log.d(TAG, "sendVideoList: videoList is" + videoList.get(2).getVideoName());
        }


        public byte[] sendMusicImage(int Index) {
            currentMediaIndex = Index;
            Log.d(TAG, "sendMusicImage: currentMediaIndex is " + currentMediaIndex);
            return loadingImage(musicList.get(currentMediaIndex).getData());
        }


    }

    public void AutoPlay(){
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

            }
        });
    }

    //播放器命令通知函数

    //接收客户端发的命令解析，并传递改变播放状态信息给UI,
    public void recvOrderMessage(String Jstr) {
        Order order = Order.parseJson(Jstr);
//		System.out.println("命令为 "+order.code);
//		System.out.println("命令信息为 " +order.clientMsg);
        OrderMessage orderMsg = OrderMessage.parseJson(order.clientMsg);
//		System.out.println("播放模式为" + orderMsg.mode);
        Params params = Params.parseToJson(orderMsg.orderMsg);
//        System.out.println("param 1 is " + param.mParams.get(1).value);

        switch (order.code) {
            case ORDER_PLAY:
                try{
                    if (params.mParams.size() > 0) {
                        Params.Param p = params.mParams.get(0);
                  //      if (InstructionList.PARAM.CURRENT_MEDIAINDEX.equals(p.name)) {
                            currentMediaIndex =  Integer.parseInt(p.value);
                            Log.d(TAG, "recvOrderMessage: onCLick currrentMusicIndex is " + currentMediaIndex);
                            orderPlay(orderMsg.mode);
                 //       }
                    }

            }catch (Exception e){
                e.printStackTrace();
            }
                break;
            case ORDER_CONTINUE:
                try{
                    Log.d(TAG, "recvOrderMessage: 继续播放");
                    orderContinue(orderMsg.mode);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case ORDER_PAUSE:
                Log.d(TAG, "recvOrderMessage: 暂停命令");
                try{
                    orderPause(orderMsg.mode);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case ORDER_PREVIOUS:
                try{
                orderPrevious(orderMsg.mode);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case ORDER_NEXT:
                try{
                    orderNext(orderMsg.mode);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case ORDER_BACK:
                try{
                    orderBack();
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case GET_LIST:
                if (params.mParams.size() >= 2) {
                    Params.Param p1 = params.mParams.get(0);
                    Params.Param p2 = params.mParams.get(1);
                    int start_no = 0;
                    int page_size = 10;

                    Log.d(TAG, "GET_LIST p1: " + p1.name + " " + p1.value);
                    Log.d(TAG, "GET_LIST p2: " + p2.name + " " + p2.value);

                    if (InstructionList.PARAM.START_NO.equals(p1.name)) {
                        start_no = Integer.parseInt(p1.value);
                    }
                    if (InstructionList.PARAM.PAGE_SIZE.equals(p2.name)) {
                        page_size = Integer.parseInt(p2.value);
                    }
                    try {
                        switch (orderMsg.mode) {
                            case MODE_MUSIC:
                                initMusicService();                     //初始化服务端音乐播放器
                                mHandlerMedia.sendEmptyMessage(MODE_MUSIC);
                                //发送音乐列表给客户端
                                socketServer.sendMsg2(sendListMessage(MEDIA_TYPE_MUSIC, getMusicList(musicList), start_no, page_size));
//                                Log.d(TAG, "recvOrderMessage: is " + sendListMessage(MEDIA_TYPE_MUSIC, getMusicList(musicList)));
                                break;
                            case MODE_VIDEO:
                                //初始化服务端视频播放器
                                initVideoService();
                                mHandlerMedia.sendEmptyMessage(MODE_VIDEO);                  //通知视频播放器初始化

                                //发送视频列表给客户端
                                Log.d(TAG, "recvOrderMessage: 已经运行到发送列表");
//                            Log.d(TAG, "recvOrderMessage: videoList is " + getVideoList(videoList).get(58).toString());
                                //   Log.d(TAG, "recvOrderMessage: 视频列表以获得" + getVideoList());
                                socketServer.sendMsg2(sendListMessage(MEDIA_TYPE_VIDEO, getVideoList(videoList), start_no, page_size));

                                break;
                            default:
                                break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                break;
            default:
                break;

        }

    }

    public static List<Object> getMusicList(List<Music> list) {
        List<Object> newList = new ArrayList<>();
        for (Music m: list) {
            newList.add(m);
        }
        return newList;
    }

    public static List<Object> getVideoList(List<Video> list){
        List<Object> newList = new ArrayList<>();
        Log.d(TAG, "getVideoList: list.get(10).toString() is " + list.get(2).toString());
        for (Video v: list){
            newList.add(v);
        }
        return newList;
    }



    //初始化音乐播放器
    public void initMusicService() {
        getSong();
        Running = true;
        initMusicIsplayingThread();
    }
    //初始化视频播放器
    public void initVideoService(){
        instance = this;
        AbstructProvider provider = new VideoProvider(instance);
        videoList = provider.getList();
        //Log.d("ttttttttttt", "initVideoService: " + videoList.get(2).getVideoName());
    }

    //发送进度信息给UI界面，并自动播放下一首，将信息传递给UI
    //音乐
    public void initMusicIsplayingThread() {
        MusicIsPlayingThread musicIsPlayingThread = new MusicIsPlayingThread();
        new Thread(musicIsPlayingThread).start();
    }


    //改变播放状态基础函数
    public void play() {

        if (currentMediaIndex == -1) {
            currentMediaIndex = 0;
            initMediaPlayer();
        } else {
            initMediaPlayer();
        }
    }

    public void pause() {
        pauseTrue = true;
        mediaPlayer.pause();
    }

    public void goOn(){
        mediaPlayer.start();
        Log.d(TAG, "orderContinue: 真的播放了");
    }

    public void previous() {
        if (currentMediaIndex == 0) {
            currentMediaIndex = musicList.size() - 1;
            initMediaPlayer();
        } else {
            currentMediaIndex--;
            initMediaPlayer();
        }
    }

    public void next() {
//        Log.d("FFFFFFFFFFFFFFFFFFF", "on nexttttttt!!!!" + Log.getStackTraceString(new Throwable("next")));
        if (currentMediaIndex == musicList.size() - 1) {
            currentMediaIndex = 0;
            initMediaPlayer();
        } else {
            currentMediaIndex++;
            initMediaPlayer();
        }
    }


    public void stop() {
        mediaPlayer.stop();
        Running = false;

    }

    public void reset() {
        mediaPlayer.reset();
    }


    //order系列命令是传递客户端的改变播放状态和UI的命令给UI
    public void orderBack(){
        mHandlerMedia.sendEmptyMessage(ORDER_BACK);
    }

    public void orderContinue(int MODE){
        switch (MODE){
            case MODE_MUSIC:
                Log.d(TAG, "orderContinue: 音乐播放");
                goOn();
                Message message = new Message();
                message.what = ORDER_CONTINUE;
                message.arg1 = currentMediaIndex;
                mHandlerMedia.sendMessage(message);
                break;
            case MODE_VIDEO:
                mHandlerMedia.sendEmptyMessage(ORDER_CONTINUE);
                break;
                default:
                    break;
        }
    }

    public void orderPlay(int MODE) {
        Message message = new Message();
        switch (MODE){
            case MODE_MUSIC:
                play();
                message.what = ORDER_PLAY;
                message.arg1 = currentMediaIndex;
                mHandlerMedia.sendMessage(message);
                break;
            case MODE_VIDEO:
                message.what = ORDER_PLAY;
                message.arg1 = currentMediaIndex;
                mHandlerMedia.sendMessage(message);
                break;
                default:
                    break;
        }

    }

    public void orderPause(int MODE) {
        switch (MODE){
            case MODE_MUSIC:
                pause();
                Log.d(TAG, "orderPause: 暂停了");
                mHandlerMedia.sendEmptyMessage(ORDER_PAUSE);
                break;
            case MODE_VIDEO:
                mHandlerMedia.sendEmptyMessage(ORDER_PAUSE);
                break;
            default:
                break;
        }

    }

    public void orderPrevious(int MODE) {
        Message message = new Message();
        switch (MODE){
            case MODE_MUSIC:
                previous();
                message.what = ORDER_PREVIOUS;
                message.arg1 = currentMediaIndex;
                mHandlerMedia.sendMessage(message);
                break;
            case MODE_VIDEO:

                message.what = ORDER_PREVIOUS;
                mHandlerMedia.sendMessage(message);
                break;
            default:
                break;
        }

    }

    public void orderNext(int MODE) {
        switch (MODE){
            case MODE_MUSIC:
                next();
                Message message = new Message();
                message.what = ORDER_NEXT;
                message.arg1 = currentMediaIndex;
                mHandlerMedia.sendMessage(message);
                break;
            case MODE_VIDEO:
                mHandlerMedia.sendEmptyMessage(ORDER_NEXT);
                break;
            default:
                break;
        }

    }

    //接收UI界面进度条位置并跳转
    public void changeProgress(int position) {
        mediaPlayer.seekTo(position);
    }

    //音乐播放器播放进程
    private void initMediaPlayer() {
        Log.d(TAG, "initMediaPlayer: playing index is " + currentMediaIndex);
        pauseTrue = false;
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(musicList.get(currentMediaIndex).getData());
            mediaPlayer.prepare();
            mediaPlayer.start();
            //      currentMusicTv.setText(musicList.get(currentMediaIndex).getMusicName() + musicList.get(currentMediaIndex).getArtist());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //加载专辑图片
    private byte[] loadingImage(String mediaUrl) {
        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(mediaUrl);
        Log.d(TAG, "loadingImage: mediaUrl is " + mediaUrl);
        byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
        //   Log.d(TAG, "loadingImage: is " + picture.length);
        return picture;

    }

    //本地得到音乐列表
    private void getSong() {
        int id = 0;
        Log.d(TAG, "getSong: ");
        contentResolver = getContentResolver();
        mCursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DURATION,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DISPLAY_NAME},
                null,
                null,
                null);
        musicList.clear();
        for (int i = 0; i < mCursor.getCount(); i++) {
            Music music = new Music();
            mCursor.moveToNext();
            if (mCursor.getInt(mCursor.getColumnIndex(MediaStore.Audio.Media.DURATION)) < 400000 && mCursor.getInt(mCursor.getColumnIndex(MediaStore.Audio.Media.DURATION)) > 150000) {
                music.setId(id);
                music.setDuration(mCursor.getInt(mCursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
                music.setArtist(mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
                music.setData(mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
                // music.setDuration();
                music.setMusicName(mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
                musicList.add(music);
                id++;
            }
        }

    }


    //发送列表给客户端
    public static String sendListMessage(int type, List<Object> mList, int start_no, int page_size) {
        List<Object> new_list = new ArrayList<>();
        if (mList != null && mList.size() >= start_no) {
            int max_size = Math.min(start_no + page_size, mList.size());
            for (int i = start_no; i < max_size; ++i) {
                Log.d(TAG, mList.get(i).toString());
                new_list.add(mList.get(i));
            }
        }

        MediaList mediaList = new MusicList();
        mediaList.setType(type);
        mediaList.mList = new_list;
        Messages message = new Messages();
        message.setOrder(GET_LIST);
        message.setResult(true);
        message.setMsg(MediaList.packToJson(mediaList));
        String res = Messages.packToJson(message);
        Log.d(TAG, "sendListMessage" + res.length());
        return res;
    }

    //音乐播放进度和自动播放线程
    public class MusicIsPlayingThread implements Runnable {
        @Override
        public void run() {
            while (Running) {

                try {
                    Thread.sleep(1000);
                    boolean isplaying = mediaPlayer.isPlaying();
                 //   Log.d(TAG, "run: isPlaying" + isplaying);
                 //   if (!pauseTrue) {
                        if (isplaying) {
                            Message message = new Message();
                            message.what = ORDER_CURRENTDURATION;
                            message.arg1 = mediaPlayer.getCurrentPosition();//传递当前的位置信息
                            message.arg2 = currentMediaIndex;               //传递当前索引
                            Log.d(TAG, "run: currentMusicPosition is " + message.arg1);
                            mHandlerMedia.sendMessage(message);
                        } else {
                          //  next();
                          //  Message message = new Message();
                          //  message.what = ORDER_ISSTOP;  //传递音乐未播放信息给UI
                          //  mHandlerMedia.sendEmptyMessage(ORDER_ISSTOP);
                        }
                 //   }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

